'use strict';
define(['angular', 'base64', 'common/utils/rest'], function (angular, base64) {
	var module = angular.module('blockingRestService', ['mpjRest']);

	var httpRequestInProgress = 0;
	module.factory('blockingRestService', [
		'mpjRest', '$rootScope',
		function (mpjRest, $rootScope) {
			return {
				post: post,
				put: put,
				get: get,
				delete: deleteData
			};
			function commonality(cb1, ownError) {
				var cb = function (err, data) {
				    if (err&&!(ownError||{}).ownError) {
				        $rootScope.error = err;
				    }
					httpRequestInProgress--;
					if (httpRequestInProgress <= 0)
						$rootScope.handleComplete();
					cb1 && cb1(err, data);
				}
				httpRequestInProgress++;
				$rootScope.handleWaiting();
				return cb;
			}

			function post(url, data, config, cb1, ownError) {
				var cbIndex = 3;
				if (typeof config === 'function') {
					cbIndex = 2;
				}
				arguments[cbIndex] = commonality(arguments[cbIndex]);
				return mpjRest.post.apply(this, arguments);
			}

			function get(url, cb1, ownError) {
				var cb = commonality(cb1, ownError);
				return mpjRest.get(url, cb, ownError);
			}

			function put(url, data, cb1, ownError) {
				var cb = commonality(cb1);
				return mpjRest.put(url, data, cb, ownError);
			}

			function deleteData(url, config, cb1, ownError) {
				var cb = commonality(cb1);
				return mpjRest.delete(url, config, cb, ownError);
			}
		}]);
	// todo move to another module
	module.run(['$rootScope', function ($rootScope) {
		$rootScope.handleWaiting = function () {
			$rootScope.pageDataLoading = true;
		}

		$rootScope.handleComplete = function () {
			$rootScope.pageDataLoading = false;
		}
	}])
	return module;
});
